import { API_CONFIG } from '../config/constants';

export class SessionService {
    /**
     * 创建新会话
     * @returns {Promise<string>} 返回新会话的ID
     */
    static async createSession() {
        try {
            console.log('➕ 创建会话请求URL:', API_CONFIG.CREATE_SESSION_URL);
            
            const response = await fetch(API_CONFIG.CREATE_SESSION_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    id: "",
                    title: "",
                    status: "",
                    isPinned: 0,
                    userId: 0,
                    createTime: "",
                    updateTime: ""
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            
            if (result.code === 0 && result.data) {
                return result.data; // 返回会话ID
            } else {
                throw new Error(result.message || '创建会话失败');
            }
        } catch (error) {
            console.error('创建会话失败:', error);
            throw error;
        }
    }

    /**
     * 获取会话列表
     * @param {number} userId 用户ID
     * @returns {Promise<Array>} 会话列表
     */
    static async getSessions(userId = 0) {
        try {
            const getSessionsUrl = `${API_CONFIG.GET_SESSIONS_URL}?userId=${userId}`;
            console.log('📋 获取会话列表请求URL:', getSessionsUrl);
            
            const response = await fetch(getSessionsUrl, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            
            if (result.code === 0 && Array.isArray(result.data)) {
                return result.data; // 返回完整的会话列表
            } else {
                throw new Error(result.message || '获取会话列表失败');
            }
        } catch (error) {
            console.error('获取会话列表失败:', error);
            // 重新抛出错误，让上层组件能够处理网络问题
            if (error.message.includes('Failed to fetch')) {
                throw new Error('网络连接失败，请检查服务器是否正常运行');
            }
            throw error;
        }
    }

    /**
     * 删除会话
     * @param {string} sessionId 会话ID
     * @returns {Promise<boolean>} 是否删除成功
     */
    static async deleteSession(sessionId) {
        try {
            const deleteUrl = API_CONFIG.DELETE_SESSION_URL(sessionId);
            console.log('🗑️ 删除会话请求URL:', deleteUrl);
            
            const response = await fetch(deleteUrl, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            
            if (result.code === 0) {
                return result.data; // 返回删除结果 (true/false)
            } else {
                throw new Error(result.message || '删除会话失败');
            }
        } catch (error) {
            console.error('删除会话失败:', error);
            throw error;
        }
    }

    /**
     * 复制会话
     * @param {string} sessionId 会话ID
     * @returns {Promise<string>} 返回新复制会话的ID
     */
    static async copySession(sessionId) {
        try {
            const copyUrl = API_CONFIG.COPY_SESSION_URL(sessionId);
            console.log('📋 复制会话请求URL:', copyUrl);
            
            const response = await fetch(copyUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();

            if (result.code === 0 && result.data) {
                return result.data; // 返回新复制会话的ID
            } else {
                throw new Error(result.message || '复制会话失败');
            }
        } catch (error) {
            console.error('复制会话失败:', error);
            throw error;
        }
    }

    /**
     * 更新会话标题
     * @param {string} sessionId 会话ID
     * @param {string} title 新标题
     * @param {Object} sessionData 会话数据
     * @returns {Promise<boolean>} 是否更新成功
     */
    static async updateSession(sessionId, title, sessionData) {
        try {
            const updateUrl = API_CONFIG.UPDATE_SESSION_URL(sessionId);
            console.log('✏️ 更新会话请求URL:', updateUrl);
            
            const response = await fetch(updateUrl, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    id: sessionId,
                    title: title,
                    status: sessionData.status || "",
                    isPinned: sessionData.isPinned || 0,
                    userId: sessionData.userId || 0,
                    createTime: sessionData.createTime || "",
                    updateTime: sessionData.updateTime || ""
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();

            if (result.code === 0) {
                return result.data; // 返回更新结果 (true/false)
            } else {
                throw new Error(result.message || '更新会话失败');
            }
        } catch (error) {
            console.error('更新会话失败:', error);
            throw error;
        }
    }
}